package com.my.ads.lib;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.ads.AbstractAdListener;
import com.facebook.ads.Ad;
import com.facebook.ads.AdChoicesView;
import com.facebook.ads.AdError;
import com.facebook.ads.InterstitialAd;
import com.facebook.ads.InterstitialAdListener;
import com.facebook.ads.NativeAd;
import com.facebook.ads.NativeAdsManager;
import com.my.ads.lib.bean.BeanList;
import com.my.ads.lib.bean.FbNativeAd;
import com.my.ads.lib.utils.Utils;
import com.my.ads.lib.view.CustomMediaView;
import com.rapid.clean.deep.R;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by xuanyang on 2018/3/2.
 */

public class FbUtils {

    private List<InterstitialAd> mListInterstitialAdEcpm = new ArrayList<>();
    private List<InterstitialAd> mListInterstitialAd = new ArrayList<>();

    private static FbUtils instance = new FbUtils();

    private static long mAdTimes;
    private long NoFillTime = 0L;
    private long TooRequestTime = 0L;


    private Button cta;
    private TextView adTitle;
    private ImageView adIcon;
    private CustomMediaView adMedia;
    private TextView adSocial;
    private TextView body;


    public static FbUtils getInstance() {
        return instance;
    }

    public void cacheFbInterstitialAd(Context context, List<InterstitialAd> listInterstitialAd, String facebookAdKey) {

        try {
            if (!Utils.checkApkExist(context)) {
                return;
            }
            if (TextUtils.isEmpty(facebookAdKey)) {
                return;
            }

            if (listInterstitialAd.size() <= 5) {
                requestInterstitialAd(context, listInterstitialAd, facebookAdKey);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    private void requestInterstitialAd(Context context, final List<InterstitialAd> listInterstitialAd, String facebookAdKey) {


        try {
            final InterstitialAd interstitialAd = new InterstitialAd(context, facebookAdKey);
            interstitialAd.setAdListener(new InterstitialAdListener() {
                @Override
                public void onInterstitialDisplayed(Ad ad) {
                }

                @Override
                public void onInterstitialDismissed(Ad ad) {
                    // Interstitial dismissed callback
                }

                @Override
                public void onError(Ad ad, AdError adError) {
                    // Ad error callback
                }

                @Override
                public void onAdLoaded(Ad ad) {
                    // Show the ad when it's done loading.

                    if (interstitialAd != null) {
                        listInterstitialAd.add(0, interstitialAd);
                    }
                }

                @Override
                public void onAdClicked(Ad ad) {
                    // Ad clicked callback
                }

                @Override
                public void onLoggingImpression(Ad ad) {
                    // Ad impression logged callback
                }
            });

            interstitialAd.loadAd();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    public void cacheFbNativeAd() {

    }


    /**
     * 缓存fb native
     */
    public void LoadEcpmPriorityFbNative(Context context, final String facebookEcpmNativeKey) {


        if (!Utils.checkApkExist(context)) {
            return;
        }

        final long now = System.currentTimeMillis();

        if (Math.abs(now - mAdTimes) <= 60 * 1000) { // 60秒内不重复加载
            return;
        }

        // 请求过于频繁
        if (Math.abs(now - TooRequestTime) <= 60 * 60 * 1000) {
            return;
        }

        // 请求无填充
        if (Math.abs(now - NoFillTime) <= 10 * 60 * 1000) { // 所有广告位都发生 AdError.NO_FILL_ERROR_CODE 赋值
            return;
        }

//        int num = JobScheduleTools.getAdNumForHalfHour(BeanList.mNativeCache); // 30分钟内最多缓存16个广告
//        int mMaxAdNum = 16;
//        if (num >= mMaxAdNum) {
//            return;
//        }

        int num = Utils.getNotShowAdNum(BeanList.mNativeCache); // 30分钟内超过5次不展示广告则停止流程
        if (num > 5) {
            return;
        }

        try {
            requestNativeAd(context, facebookEcpmNativeKey);
        } catch (Exception ignore) {

        }
    }


    private void requestNativeAd(Context context, final String facebookEcpmNativeKey) {

        final NativeAdsManager adsManager = new NativeAdsManager(context, facebookEcpmNativeKey, 3);
        final NativeAdsManager.Listener listener = new NativeAdsManager.Listener() {

            @Override
            public void onAdsLoaded() {
                cacheFbNativeAd(adsManager);
            }

            @Override
            public void onAdError(AdError adError) {
                errorTime(adError);
            }
        };

        adsManager.setListener(listener);
        adsManager.loadAds(NativeAd.MediaCacheFlag.ALL);
    }


    private void cacheFbNativeAd(NativeAdsManager adsManager) {

        //////////////////////////////////////////////////////////////////////
        BeanList.mNativeCache = Utils.removeAdByTimeout(BeanList.mNativeCache);
        BeanList.mNativeCache = Utils.removeAdByShow(BeanList.mNativeCache);
        //////////////////////////////////////////////////////////////////////

        mAdTimes = System.currentTimeMillis();
        int count = adsManager.getUniqueNativeAdCount();
        for (int i = 0; i < count; i++) {
            NativeAd item = adsManager.nextNativeAd();
            if (item != null && item.isAdLoaded()) {
                FbNativeAd ad = new FbNativeAd();
                ad.setNativeAd(item);
                ad.setAdTime(System.currentTimeMillis());
                ad.setHasShowed(false);
                BeanList.mNativeCache.add(0, ad);
            }
        }

    }

    private void errorTime(AdError adError) {

        if (adError.getErrorCode() == AdError.LOAD_TOO_FREQUENTLY_ERROR_CODE) {
            TooRequestTime = System.currentTimeMillis();
        } else if (adError.getErrorCode() == AdError.NO_FILL_ERROR_CODE) {
            NoFillTime = System.currentTimeMillis();
        }
    }


    public void showFbNative(final Context context, final RelativeLayout parent, final int position, final boolean isFromLockScreen) {
        NadShows(context, parent, position, isFromLockScreen);
    }

    public void showSmallNative(final Context context, final RelativeLayout parent) {
        showSmallFbNativeAd(context, parent);
    }


    private void showNewInterstitialAd(Context context, List<InterstitialAd> list) {

        if (list.get(0) != null) {

            list.get(0).show();
            list.remove(0);

            SharedPreferences sp = context.getSharedPreferences("Adinter", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();

            editor.putLong("time_show", System.currentTimeMillis());
            editor.apply();
        }
    }

    //展示facebook的原生广告  ecpm
    public void NadShows(final Context context, final RelativeLayout parent, final int position, final boolean isFromLockScreen) {

        if (!Utils.checkApkExist(context)) {
            AdxUtils.getInstance().adxNativeShow(context, parent, position + 1, false, 0);
            return;
        }
        if (parent.getChildCount() != 0) {
            parent.removeAllViews();
        }
        showFbAd(context, parent, position, isFromLockScreen, 0);
    }


    public void showFbAd(final Context context, final RelativeLayout parent, final int position, final boolean isFromLockScreen, final int first) {

        final View adView = LayoutInflater.from(context)
                .inflate(R.layout.fb_na_layout, parent, false);
        parent.addView(adView);
        parent.setVisibility(View.GONE);
        cta = (Button) adView.findViewById(R.id.native_ad_call_to_action);
        adSocial = (TextView) adView.findViewById(R.id.native_ad_social_context);
        adTitle = (TextView) adView.findViewById(R.id.native_ad_title);
        adMedia = (CustomMediaView) adView.findViewById(R.id.native_ad_media_xc);
        adIcon = (ImageView) adView.findViewById(R.id.native_ad_icon);
        body = (TextView) adView.findViewById(R.id.native_ad_body);
        if (first == 0) {
            if (BeanList.mNativeCache == null || BeanList.mNativeCache.isEmpty()) {
                showFbAd(context, parent, position, isFromLockScreen, 1);
            } else {
                final NativeAd nativeAdView = BeanList.mNativeCache.get(0).getNativeAd();
                if (nativeAdView != null) {
                    natives(BeanList.mNativeCache, context, parent, isFromLockScreen, nativeAdView, adView);
                } else {
                    showFbAd(context, parent, position, isFromLockScreen, 1);

                }
            }
        } else if (first == 1) {
            if (BeanList.mNativeCache_fill == null || BeanList.mNativeCache_fill.isEmpty()) {
                AdSummary.getInstance().showNativeAd(context, parent, false); // 这里有问题哈
            } else {
                final NativeAd nativeAdView = BeanList.mNativeCache_fill.get(0).getNativeAd();

                if (nativeAdView != null) {
                    natives(BeanList.mNativeCache_fill, context, parent, isFromLockScreen, nativeAdView, adView);
                } else {
                    AdSummary.getInstance().showNativeAd(context, parent, false);
                }
            }
        }

    }

    private void natives(final List<FbNativeAd> list_fbNativeAd, final Context context, final RelativeLayout parent, final boolean isFromLockScreen, NativeAd nativeAdView, View adView) {
        parent.setVisibility(View.VISIBLE);
        nativeAdView.unregisterView();
        BeanList.mNativeCache_fill.get(0).setHasShowed(true);
        adTitle.setText(nativeAdView.getAdTitle());
        adSocial.setText(nativeAdView.getAdSocialContext());
        body.setText(nativeAdView.getAdBody());
        cta.setText(nativeAdView.getAdCallToAction());
        NativeAd.Image adIcon = nativeAdView.getAdIcon();
        NativeAd.downloadAndDisplayImage(adIcon, this.adIcon);
        adMedia.setNativeAd(nativeAdView);
        LinearLayout adChoicesContainer = (LinearLayout) adView.findViewById(R.id.ad_choices_container);
        AdChoicesView adChoicesView = new AdChoicesView(context, nativeAdView, true);
        adChoicesContainer.addView(adChoicesView);
        List<View> clickableViews = new ArrayList<>();
        clickableViews.add(adTitle);
        clickableViews.add(this.adIcon);
        clickableViews.add(adMedia);
        clickableViews.add(cta);
        nativeAdView.setAdListener(new AbstractAdListener() {

            @Override
            public void onAdClicked(Ad ad) {
                if (isFromLockScreen) {
                    ((Activity) context).finish();
                }
            }

        });
        nativeAdView.registerViewForInteraction(parent, clickableViews);
        list_fbNativeAd.remove(0);
    }


    //展示facebook的原生广告
    public void showSmallFbNativeAd(final Context context, final RelativeLayout nativeAdContainer) {

        if (!Utils.checkApkExist(context)) {
            return;
        }
        LayoutInflater inflater = LayoutInflater.from(context);
        View adView = (LinearLayout) inflater.inflate(R.layout.little_fb_na, nativeAdContainer, false);
        nativeAdContainer.removeAllViews();
        nativeAdContainer.addView(adView);
        adIcon = (ImageView) adView.findViewById(R.id.native_ad_icon);
        adTitle = (TextView) adView.findViewById(R.id.native_ad_title);
        cta = (Button) adView.findViewById(R.id.native_ad_call_to_action);
        nativeAdContainer.setVisibility(View.GONE);
        if (BeanList.mNativeCache != null && BeanList.mNativeCache.size() > 0) {
            if (BeanList.mNativeCache.get(0).getNativeAd() != null) {
                smallNatives(BeanList.mNativeCache, nativeAdContainer, adView, context);
            }
        } else if (BeanList.mNativeCache_fill != null && BeanList.mNativeCache_fill.size() > 0) {
            if (BeanList.mNativeCache_fill.get(0).getNativeAd() != null) {
                smallNatives(BeanList.mNativeCache_fill, nativeAdContainer, adView, context);
            }
        } else {
            AdxUtils.getInstance().showAdxBanner(nativeAdContainer);
        }
    }

    private void smallNatives(final List<FbNativeAd> list_fbNativeAd, final RelativeLayout nativeAdContainer, View adView, Context context) {
        nativeAdContainer.setVisibility(View.VISIBLE);
        BeanList.mNativeCache_fill.get(0).getNativeAd().unregisterView();
        BeanList.mNativeCache_fill.get(0).setHasShowed(true);
        adTitle.setText(BeanList.mNativeCache_fill.get(0).getNativeAd().getAdTitle());
        cta.setText(BeanList.mNativeCache_fill.get(0).getNativeAd().getAdCallToAction());
        // Download and display the ad icon.
        NativeAd.Image adIcons = BeanList.mNativeCache_fill.get(0).getNativeAd().getAdIcon();
        NativeAd.downloadAndDisplayImage(adIcons, adIcon);
        // Add the AdChoices icon
        LinearLayout adChoicesContainer = (LinearLayout) adView.findViewById(R.id.ad_choices_container);
        AdChoicesView adChoicesView = new AdChoicesView(context, BeanList.mNativeCache_fill.get(0).getNativeAd(), true);
        adChoicesContainer.addView(adChoicesView);
        // Register the Title and CTA button to listen for clicks.
        List<View> clickableViews = new ArrayList<>();
        clickableViews.add(adTitle);
        clickableViews.add(cta);
        clickableViews.add(adIcon);
        list_fbNativeAd.get(0).getNativeAd().registerViewForInteraction(nativeAdContainer, clickableViews);
        list_fbNativeAd.remove(0);

    }


}
